package com.naihe.anderson.sms.manager;

import java.util.ArrayList;
import java.util.List;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.SystemClock;
import android.widget.Toast;

import com.naihe.anderson.sms.R;
import com.naihe.anderson.sms.application.NhSmsApp;
import com.naihe.anderson.sms.broadcastReceiver.SignatureMsgSendReceiver;
import com.naihe.anderson.sms.entity.SignatureMsg;
import com.naihe.anderson.sms.listener.OnSignatureMsgChangeListener;
import com.naihe.anderson.sms.service.NhSmsMainService;
import com.naihe.anderson.sms.util.DateTimeUtil;
import com.naihe.anderson.sms.util.FileUtil;
import com.naihe.anderson.sms.util.ObjectUtil;
import com.naihe.anderson.sms.xml.SignatureXmlUtil;

public class SignatureMsgMgr {

	NhSmsApp application;
	
	List<SignatureMsg> signatureMsgs;
	AlarmManager alarmManager;
	
	OnSignatureMsgChangeListener listener;
	
	public void setListener(OnSignatureMsgChangeListener listener){
		this.listener = listener;
	}
	
	public SignatureMsgMgr(NhSmsApp app){
		this.application = app;
		signatureMsgs = new ArrayList<SignatureMsg>();
		alarmManager = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
	}
	
	public void init(){
		new FirstGetSignatureMsgInfoTask().execute();
	}
	
	public List<SignatureMsg> getSignatureMsgInfo(){
		return signatureMsgs;
	}
	
	public void startMainService() {
		Intent mainServiceIntent = new Intent(application, NhSmsMainService.class);
		application.startService(mainServiceIntent);
	}
	
	public void setAlarmManager(long signatureMsgId, long differTime){
		Intent intent = new Intent(SignatureMsgSendReceiver.SIGNATURE_SEND_RECEIVER_ACTION);
		intent.putExtra("signatureMsgId", signatureMsgId);
		PendingIntent sender = PendingIntent.getBroadcast(application, (int)signatureMsgId/1000, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		if(alarmManager == null)
			alarmManager = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
		long sendTime = SystemClock.elapsedRealtime() + differTime;
		alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, sendTime, sender);
		
		Toast.makeText(application, application.getResources().getString(R.string.msg_send_time, DateTimeUtil.getCountdown(differTime)), Toast.LENGTH_LONG).show();
		FileUtil.addLog("SignatureMsgMgr::setAlarmManager() signatureMsgId=" + signatureMsgId+ " || sendTime=" + sendTime + " || differTime=" + differTime, SignatureMsgMgr.class, "SignatureMsgMgr", null);
	}
	
	public void cancalAlarmManager(long signatureMsgId){
		Intent intent = new Intent(SignatureMsgSendReceiver.SIGNATURE_SEND_RECEIVER_ACTION);
		intent.putExtra("signatureMsgId", signatureMsgId);
		PendingIntent sender = PendingIntent.getBroadcast(application, (int)signatureMsgId/1000, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		if(alarmManager == null)
			alarmManager = (AlarmManager)application.getSystemService(Context.ALARM_SERVICE);
		alarmManager.cancel(sender);
		
		FileUtil.addLog("SignatureMsgMgr::cancalAlarmManager() signatureMsgId=" + signatureMsgId, SignatureMsgMgr.class, "SignatureMsgMgr", null);
	}
	
	@SuppressWarnings("unchecked")
	public void saveSignatureMsgInfo(SignatureMsg msg){
		signatureMsgs.add(msg);
		
		if(listener != null) listener.OnSignatureMsgChange();
		setAlarmManager(msg.getSignatureMsgId(), msg.getSignatureMsgTime() - System.currentTimeMillis());
		new SaveSignatureMsgInfoTask((List<SignatureMsg>)ObjectUtil.copySerializableObj(signatureMsgs)).execute();
	}
	
	public SignatureMsg getSignatureMsgInfoById(long signatureMsgId){
		for(SignatureMsg msg : signatureMsgs){
			if(msg.getSignatureMsgId() == signatureMsgId){
				return msg;
			}
		}
		
		return null;
	}
	
	@SuppressWarnings("unchecked")
	public void updateSignatureMsgInfo(SignatureMsg signatureMsg, boolean ifChangeAlarm){
		for(SignatureMsg msg : signatureMsgs){
			if(msg.getSignatureMsgId() == signatureMsg.getSignatureMsgId()){
				signatureMsgs.remove(msg);
				signatureMsgs.add(0, signatureMsg);
				
				if(ifChangeAlarm){
					cancalAlarmManager(signatureMsg.getSignatureMsgId());
					long differTime = signatureMsg.getSignatureMsgTime() - System.currentTimeMillis();
					setAlarmManager(signatureMsg.getSignatureMsgId(), differTime);
				}
				
				break;
			}
		}
		if(listener != null) listener.OnSignatureMsgChange();
		new SaveSignatureMsgInfoTask((List<SignatureMsg>)ObjectUtil.copySerializableObj(signatureMsgs)).execute();
	}
	
	@SuppressWarnings("unchecked")
	public void removeSignatureMsgInfo(SignatureMsg signatureMsg){
		for(SignatureMsg msg : signatureMsgs){
			if(msg.getSignatureMsgId() == signatureMsg.getSignatureMsgId()){
				signatureMsgs.remove(msg);
				if(msg.getSignatureMsgStatut() == SignatureMsg.SIGNATUREMSG_STATUT_COMPLETE)
					cancalAlarmManager(signatureMsg.getSignatureMsgId());
				
				alarmManager = null;
				break;
			}
		}
		if(listener != null) listener.OnSignatureMsgChange();
		new SaveSignatureMsgInfoTask((List<SignatureMsg>)ObjectUtil.copySerializableObj(signatureMsgs)).execute();
	}

	
	//=====================================================================================================================
	
	
	class FirstGetSignatureMsgInfoTask extends AsyncTask<Object, Object, Object>{
		List<SignatureMsg> tempList;
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Object doInBackground(Object... arg0) {
			tempList = new ArrayList<SignatureMsg>();
			tempList.addAll(new SignatureXmlUtil().getSignatureMsgByXml(application));
			return true;
		}
		
        protected void onPostExecute(Object result) {
        	signatureMsgs.clear();
        	signatureMsgs.addAll(tempList);
        	
        	tempList.clear();
        	tempList = null;
        	
        	startMainService();
        }		
	}
	
	class SaveSignatureMsgInfoTask extends AsyncTask<Object, Object, Object>{
		List<SignatureMsg> tempList;
		
		public SaveSignatureMsgInfoTask(List<SignatureMsg> infoList){
			tempList = infoList;
		}
		@Override
		protected void onPreExecute() {
		}
		
		@Override
		protected Object doInBackground(Object... arg0) {
			new SignatureXmlUtil().saveSignatureMsg(application, tempList);
			return true;
		}
		
        protected void onPostExecute(Object result) {
        	tempList.clear();
        	tempList = null;
        }		
	}
}
